// 引入axios
import axios from 'axios'
// 引入 Element Message
import { Message } from 'element-ui'
import store from '@/store'

// 创建 axios实例
const request = axios.create({
  baseURL: 'https://likede2-admin.itheima.net/likede/',
  timeout: 5000
})

// 设置请求拦截器
request.interceptors.request.use(config => {
  // 添加Token
  config.headers.Authorization = store.state.user.token
  return config
}, error => {
  return Promise.reject(error)
})

// 设置响应拦截器
request.interceptors.response.use(response => {
  if (!response.data.success && response.data.msg) {
    Message.error(response.data.msg)
    return Promise.reject(response)
  }
  return response
}, error => {
  console.log(error)
  if (error.name === 'AxiosError') {
    if (error.response.data) {
      Message.error(error.response.data)
    } else {
      Message.error(error.message)
    }
  }
  return Promise.reject(error)
})
export default request
